import collections


class Solution:
    def minJumps(self, arr: list) -> int:
        if len(arr) <= 1:
            return 0
        table = collections.defaultdict(list)
        for i in range(len(arr)):
            table[arr[i]] += [i]
        queue = [0]
        layer = 0
        visited = set()
        visited.add(0)
        while queue:
            layer += 1
            for _ in range(len(queue)):
                i = queue.pop(0)
                candidate = []
                if i - 1 >= 0:
                    candidate.append(i - 1)
                if i + 1 < len(arr):
                    candidate.append(i + 1)
                candidate += table[arr[i]]
                isSecondTail = False
                for c in candidate:
                    if c == len(arr) - 1:
                        return layer
                    if c in visited:
                        continue
                    if c == len(arr) - 2:
                        isSecondTail = True
                    queue.append(c)
                    visited.add(c)
                if isSecondTail:
                    return layer + 1
        return layer
